package com.heima.user.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.UserVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import io.jsonwebtoken.lang.Assert;
import org.apache.catalina.User;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AppJwtUtil appJwtUtil;
    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断是用户登录还是游客登录
        String phone = dto.getPhone();
        String password = dto.getPassword();
        String username = dto.getUsername();
        ApUser user = lambdaQuery().eq(ApUser::getName,username).one();
        if(user==null){
            //为游客登录
          String token = "0";
          UserVo userVo = UserVo.builder().
                  token(token).
                  build();
        }
        Assert.notNull(user,"用户名错误");
        //2.是用户登录就校验用户名和密码校验生成jwt
         //2.1检验用户的状态信息
        if(user.getStatus().equals(1)){
            throw new RuntimeException("该用户已经被冻结");
        }
        //检验密码
        if (!passwordEncoder.matches(password,user.getPassword())){
            throw new RuntimeException("用户密码错误");
        }
        String token = AppJwtUtil.getToken((long)user.getId());
        UserVo userVo = UserVo.builder()
                .name(user.getName())
                .id(user.getId())
                .token(token)
                .phone(user.getPhone())
                .build();
        return ResponseResult.okResult(userVo);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
